package com.dict.classes;

import java.sql.ResultSet;

public class User {
	private int id;
	private String username;
	private String password;
	
	public User(){
		this.id = -1;
		this.username = "";
		this.password = "";
	}
	
	public void load(int id) throws Exception {
		UserDb db = new UserDb();
		ResultSet rs = db.loadById(id);
		while(rs.next())
		{
			this.setId(rs.getInt(1));
			this.setUsername(rs.getString(2));
			this.setPassword(rs.getString(3));
		}
		db.disconnect();
	}
	
	public int store() throws Exception 
	{			
		UserDb db = new UserDb();
		int id;
		if(this.id == -1)
			id = db.addUser(this);
		else
			id = db.updateUser(this);
		db.disconnect();
		return id;
	}
	
	public boolean delete() throws Exception
	{
		UserDb db = new UserDb();		
		boolean queryOk = db.deleteUser(this.id);
		db.disconnect();
		return queryOk;
	}
	
	public int authenticateUser() throws Exception {
		UserDb db = new UserDb();		
		ResultSet rs = db.authenticateUser(this.username, this.password);
		if(rs != null)
		{
			rs.next();
			
			return rs.getInt(1);
		}
		else
		{
			return -1;
		}
		// rs null'sa login sayfasına (false döndür, servlette yönlendir)
	}
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}
